package com.fanbuchi.app.ins.net;

import com.fanbuchi.app.ins.BuildConfig;
import com.fanbuchi.app.ins.R;
import com.fanbuchi.app.ins.app.Started;
import com.squareup.okhttp.OkHttpClient;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;

/**
 * Created by os on 16/5/12.
 * Title
 */
public class SSLConfig {
    public static void sslconfig(OkHttpClient mOkHttpClient){
        if (BuildConfig.DEBUG){
            return;
        }
        try{
            InputStream inputStream = Started.getInstance().getResources().openRawResource(R.raw.fanbuchi);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Certificate certificate = certificateFactory.generateCertificate(inputStream);

            //KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
            keyStore.setCertificateEntry("trust", certificate);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            mOkHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
            //mOkHttpClient.interceptors().add()
            mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    String domain=BuildConfig.domain;
                    if (domain.equals(hostname))
                        return true;
                    return true;
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
